import 'dart:async';

import 'package:flutter_wan_android/api/api_server.dart';
import 'package:flutter_wan_android/bean/project_list_bean.dart';
import 'package:flutter_wan_android/blocs/base/bloc_provider.dart';
import 'package:flutter_wan_android/utils/object_utils.dart';
import 'package:rxdart/rxdart.dart';

class ProjectBloc extends BaseBloc {
  BehaviorSubject<List<ProjectItem>> _subject = BehaviorSubject();

  Stream<List<ProjectItem>> get stream => _subject.stream;
  List<ProjectItem> _allData = [];

  List<ProjectItem> get allData => _allData;

  StreamSubscription<List<ProjectItem>> _streamSubscription;



  BehaviorSubject<List<ProjectItem>> _listSubject=BehaviorSubject();
  Stream<List<ProjectItem>> get listStream => _listSubject.stream;
  List<ProjectItem> _listData=[];
  List<ProjectItem> get listData =>_listData;
  StreamSubscription<List<ProjectItem>> _listStreamSubscription;


  Future getProjectList(pageIndex,cid) async{

    if (_listStreamSubscription == null) {
      _listStreamSubscription = _listSubject.listen((data) {});
    }else{
      if(_listStreamSubscription.isPaused){
        _listStreamSubscription.resume();
      }
    }


    return await ApiServer.getProjectList(pageIndex,cid: cid).then((item){

      if(_listData.length>0 && pageIndex==1){
        _listSubject.sink.add(item.datas);
        return ;
      }
      _listData.addAll(item.datas);
      _listSubject.sink.add(item.datas);

    }).catchError((error){
      _listSubject.sink.addError(error);
    });
  }




  Future getHomeProjectList(pageIndex) async {
    if (_streamSubscription == null) {
      _streamSubscription = _subject.listen((data) {});
    }else{
      if(_streamSubscription.isPaused){
        resumeProjectStream();
      }
    }
    return await ApiServer.getHomeProjectList(pageIndex).then((project) {
      if(_allData.length>0 && pageIndex==0){
        _subject.sink.add(project.datas);
        return;
      }
      _allData.addAll(project.datas);
      _subject.sink.add(project.datas);
    }).catchError((error) => _subject.sink.addError(error));
  }

  @override
  void dispose() {
    _subject.close();
    if(_listStreamSubscription!=null){
      if(!_listStreamSubscription.isPaused){
        _listStreamSubscription.pause();
      }
    }
  }

  void pauseProjectStream() {
    if (_streamSubscription != null) {
      _streamSubscription.pause();
    }
  }

  void resumeProjectStream(){
    if (_streamSubscription != null) {
      _streamSubscription.resume();
    }
  }



}
